//
//  KYNetworkTools.swift
//  01-我的微博
//
//  Created by apple on 15/7/30.
//  Copyright © 2015年 KY. All rights reserved.
//

import UIKit
import AFNetworking

/// 定义错误的类别标记
private let KYErrorDomainName = "error.network"

/// 定义网络错误类型
private enum KYNetworkError: Int {
    
    case emptyDataError = -1
    case emptyTokenError = -2
    /// 错误描述
    private var errorDescription: String {
        switch self{
        case .emptyDataError:
            return "空数据"
        case .emptyTokenError:
            return "Token 为空"
        }
    }
    
    /// 根据错误类型返回对应的错误
    private func error() -> NSError {
        return NSError(domain: KYErrorDomainName, code: rawValue, userInfo: [KYErrorDomainName : errorDescription])
    }
}

/// 网络访问方法
private enum KYNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}



/// 访问网络工具
class KYNetworkTools: AFHTTPSessionManager {
    
    //MARK: - 应用程序信息
    private let clientId = "3608379579"
    private let clientSecret = "8d72e68e997ccb48ad8bda8f2f15dd46"
    let redirectUri = "http://www.baidu.com"
    
    typealias KYNetFinashedCallBack = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    /// 单例
    static let sharedNetworkTools: KYNetworkTools = {
        
        let instance = KYNetworkTools(baseURL: NSURL(string: "https://api.weibo.com/")!)
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return instance
        }()
    
    /// 检查 Token 是否有值
    private func checkToken(finashed: KYNetFinashedCallBack) -> [String: AnyObject]? {
    
        if KYUserAccountModel.loadAccount()?.access_token == nil {
        
            let error = KYNetworkError.emptyTokenError.error()
            print(error)
            finashed(result: nil, error: error)
            return nil
        }
        return ["access_token": KYUserAccountModel.loadAccount()!.access_token!]
    }
    // MARK: - TODO
    // 加载用户信息
    func loadStatuses(finashed: KYNetFinashedCallBack) {
    
        guard let params = checkToken(finashed)else{
            return
        }
        let urlString = "2/statuses/home_timeline.json"
    
        return request(KYNetworkMethod.GET, urlString: urlString, params: params, finashed: finashed)
    }
    
    
    
    //MARK: - 加载用户数据
    /// 加载用户信息
    func loadUserInfo(uid: String, finashed: KYNetFinashedCallBack){
        
        /// 判断token 是否存在
        if KYUserAccountModel.loadAccount()?.access_token == nil {
            
            let error = KYNetworkError.emptyTokenError.error()
            print(error)
            finashed(result: nil, error: error)
            return
        }
        let urlString = "2/users/show.json"
        let params: [String: AnyObject] = ["access_token": KYUserAccountModel.loadAccount()!.access_token!, "uid":uid]
        
        // fineshed 完成回调
        request(KYNetworkMethod.GET, urlString: urlString, params: params, finashed: finashed)
    }
    
    
    /// 返回oauth 授权地址
    var oauthURL: NSURL {
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)")!
    }
    
    //MARK: - OAuth 授权
    /// 加载 Token
    func loadAccessToken(code: String, finashed: KYNetFinashedCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id":clientId,
            "client_secret":clientSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri]
        // POST 请求
        request(KYNetworkMethod.POST, urlString: urlString, params: params, finashed: finashed)
    }
    
    //MARK: - 封装AFN 网络方法 便于替换网络访问方法  降低耦合度
    
    
    
    /// 封装 GET 请求
    private func request(method: KYNetworkMethod, urlString: String, params: [String: AnyObject], finashed: KYNetFinashedCallBack){
        
        /// 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finashed(result: result, error: nil)
            }else{
                
                print("没有结果\(method) request\(urlString)")
                
                
                finashed(result: nil, error: KYNetworkError.emptyDataError.error())
            }
        }
        /// 定义失败的回调
        let failureCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            // 出现错误 回调
            print(error)
            finashed(result: nil, error: error)
        }
        
        /// 根据 method 来选择要执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failureCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failureCallBack)
        }
    }
}
